package com.qf.base.utils;

import freemarker.core.XMLOutputFormat;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import sun.misc.BASE64Encoder;


import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;


/**
 * 导出word
 */
public class WordUtil {
    private static Logger logger= LoggerFactory.getLogger(WordUtil.class);
    private static WordUtil service=null;
    private WordUtil(){super();}
    public static WordUtil getInstance(){
        if (service == null){
            synchronized (WordUtil.class){
                if (service == null){
                    service = new WordUtil();
                }
            }
        }
        return service;
    }

    /**
     * 保存临时文件到服务器
     * @param fileDir
     * @param fileName
     * @param dateMap
     * @param loadType
     * @param destFilePath
     */
    public void createTempDocFile(String fileDir, String fileName,Map<String,Object> dateMap, int loadType, String destFilePath) throws IOException, TemplateException {
        Template t=null;
        Configuration configuration=new Configuration(Configuration.VERSION_2_3_27);
        configuration.setDefaultEncoding("UTF-8");
        configuration.setOutputFormat(XMLOutputFormat.INSTANCE);
        String TMP_FILE_PATH=System.getProperty("java.io.tmpdir");
        String TMP_FILE_NAME=System.currentTimeMillis()+ UUID.randomUUID().toString().replaceAll("-","")+".ftl";
        Resource resource=new ClassPathResource(File.separator+fileDir+File.separator+fileName);
        File tmpFile=new File(TMP_FILE_PATH+File.separator+TMP_FILE_NAME);
        //路径文件
        IOUtils.copy(resource.getInputStream(),new FileOutputStream(tmpFile));
        configuration.setDirectoryForTemplateLoading(new File(TMP_FILE_PATH));
        t=configuration.getTemplate(TMP_FILE_NAME);
        File file=new File(destFilePath);
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        FileOutputStream ous=new FileOutputStream(file);
        Writer out=new BufferedWriter(new OutputStreamWriter(ous));
        t.process(dateMap,out);
        //文件生成成功
        if (out!=null){
            out.close();
            ous.close();
        }
        if (tmpFile.exists() && !tmpFile.delete()){
            System.gc();
            tmpFile.delete();
        }
        if (tmpFile.exists()){
            System.out.println("临时文件删除失败");
        }else {
            System.out.println("临时文件删除成功");
        }
    }

    /**
     * 根据路径获取字符串
     * @param filePath
     * @return
     */
    public static String getImageString(String filePath){
        InputStream in=null;
        byte[] date=null;
        try {
            in=new FileInputStream(filePath);
            date = new byte[in.available()];
            in.read(date);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in !=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        BASE64Encoder encoder=new BASE64Encoder();
        return date !=null ?encoder.encode(date):"";
    }

    /**
     * 导出文件到客户端
     * @param fileDir 模板.包名
     * @param fileName  文件名，包名所在的模板文件名
     * @param dataMap   数据
     * @param loadType  设置路径加载方式 1-绝对路径 2-项目相对路径
     * @param response  exportType 导出方式0-导出到客户端 1-在服务器创建
     * @return
     */
    public File createDocFile(String fileDir, String fileName, Map<String,Object> dataMap, int loadType, HttpServletResponse response){
        Template t=null;
        Configuration configuration=new Configuration(Configuration.VERSION_2_3_27);
        configuration.setDefaultEncoding("UTF-8");
        String TMP_FILE_PATH=System.getProperty("java.io.tmpdir");
        String TMP_FILE_NAME=System.currentTimeMillis()+ UUID.randomUUID().toString().replaceAll("-","")+".ftl";
        try {
            Resource resource=new ClassPathResource(File.separator+fileDir+File.separator+fileName);
            File tmpFile=new File(TMP_FILE_PATH+File.separator+TMP_FILE_NAME);
            FileOutputStream tmpOutStream=new FileOutputStream(tmpFile);
            IOUtils.copy(resource.getInputStream(),tmpOutStream);

            configuration.setDirectoryForTemplateLoading(new File(TMP_FILE_PATH));
            t=configuration.getTemplate(TMP_FILE_NAME);
            Writer out=null;
            response.setContentType("application/msword");
            response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("下载的文件", "UTF-8")+".doc");
            out=new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
            t.process(dataMap,out);
            //导出成功
            out.close();
            tmpOutStream.close();
            if (tmpFile.exists()&& ! tmpFile.delete()){
                System.gc();
                tmpFile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 路径替换
     */
    private String pathReplace(String path){
        while (path !=null && path.contains("\\")){
            path=path.replace("\\", "/");
        }
        return path;
    }
}
